package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Description 登录切面
 * @Author dingchunlin
 * @Date 2024/07/27 11:51
 * @Version 1.0.0
 */
@Component
@Aspect
public class GuiguLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 环绕通知，进行登录校验
     * @param joinPoint
     * @param guiguLogin
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guiguLogin)")
    public Object login(ProceedingJoinPoint joinPoint, GuiguLogin guiguLogin) throws Throwable {
        // 获取request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 从请求头中获取token
        String token = request.getHeader("token");
        // 判断token是否有效
        if (StringUtils.isEmpty(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 查询redis对应的用户id
        String customerId = (String) redisTemplate.opsForValue()
                .get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        // 设置用户id到上下文
        if (StringUtils.hasText(customerId)){
            AuthContextHolder.setUserId(Long.parseLong(customerId));
        }
        // 放行
        return joinPoint.proceed();
    }

}
